package com.job;

import com.component.domain.*;
import com.component.service.*;
import com.system.common.ContextUtils;
import com.system.config.Constants;
import com.system.job.Job;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname NoteChangeJob
 * @Description TODO
 * @Date 2023/9/27 0:20
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Job(name = "文章交换固化job")
public class NoteChangeJob {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MChannelService mChannelService;

    @Autowired
    private NoteService noteService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private MNoteSearchService mNoteSearchService;

    public void execute() throws Exception {
        List<Note> noteList=noteService.getChangeNoteList();
        List<MNoteSearch> mNotes=new ArrayList<>();
        if(noteList!=null && noteList.size() > 0){
            for (Note note : noteList) {
                MNoteSearch mNoteSearch=new MNoteSearch();
                Content content=contentService.getContentByNid(note.getId());
                if(content.getIsencrypt()){
                    String contStr= ContextUtils.decryptStr(content.getContent());
                    content.setContent(contStr);
                    mNoteSearch.setContent(contStr);
                }
                MChannel mChannel=note.getmChannel();
                mNoteSearch.setTitle(note.getTitle());
                mNoteSearch.setChannelid(mChannel.getId().toString());
                mNoteSearch.setChannelname(mChannel.getChannelname());
                String uid=note.getUserid();
                if(uid != null){
                    SysUserEntity userEntity=sysUserService.getById(uid);
                    if(userEntity != null){
                        mNoteSearch.setUid(userEntity.getUserId().toString());
                        mNoteSearch.setUsername(userEntity.getUsername());
                        mNoteSearch.setRealname(userEntity.getRealname());
                    }
                }
                mNoteSearch.setTitle(note.getTitle());
                mNoteSearch.setTag(note.getTag());
                mNoteSearch.setNid(note.getId().toString());
                mNotes.add(mNoteSearch);
                note.setStatus("1");
                noteService.updateById(note);
            }
            if(mNotes.size() > 0){
                for(MNoteSearch m : mNotes){
                    MNoteSearch mNoteSearch=mNoteSearchService.getMNoteSearchByNid(m.getNid());
                    if(mNoteSearch != null){
                        mNoteSearchService.updateById(m);
                    }else {
                        mNoteSearchService.save(m);
                    }
                   // LuceneUtils.addListDocumentByIndexName(Constants.INDEX_NAME,mNotes);
                }
            }
        }
    }
}
